package com.example.springboot_jpa.service;

import com.example.springboot_jpa.jopo.Comment;
import com.example.springboot_jpa.respository.CommentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.List;

@Service

public class CommentService {
    @Autowired
    private CommentRepository commentRepository;
    public Comment findById(Integer id){
        return commentRepository.findById(id).get();
    }
    public List<Comment> findAll(){
        return commentRepository.findAll();
    }
    public List<Comment> findAllSortByAID(){
        return commentRepository.findAll(Sort.by(Sort.Direction.DESC,"aId"));
    }
    //精确匹配查询 可多条件查询

    public List<Comment> findAllByAuthor1(String author){
        Comment comment = new Comment();
        comment.setAuthor(author);
        Example<Comment> example = Example.of(comment);
        return commentRepository.findAll(example);
    }

    //模糊匹配查询
    public List<Comment> findAllByAuthor2(String author){
        Comment comment = new Comment();
        comment.setAuthor(author);
        ExampleMatcher matcher = ExampleMatcher.matching().withMatcher("author",ExampleMatcher.GenericPropertyMatcher::contains);
        Example<Comment> example = Example.of(comment,matcher);
        return commentRepository.findAll(example);
    }
    //分页查询
    public List<Comment> findAllPage(int page, int size){
        Pageable pageable = PageRequest.of(page,size);
        return commentRepository.findAll(pageable).getContent();
    }
    public long count(){
        return commentRepository.count();
    }
    public boolean exitById(Integer id){
        return commentRepository.existsById(id);
    }
    public Comment addComment(String author, String content,Integer articleId){
        Comment comment = new Comment();
        comment.setArticleId(1);
        comment.setAuthor(author);
        comment.setContent(content);
       return commentRepository.save(comment);
    }
    public boolean deleteCommentById(Integer id){
        boolean r = true;
        try {
            commentRepository.deleteById(id);
        }catch (Exception e){
            r = false;
        }
        return r;
    }

}
